const express = require('express');
const { query } = require('express-validator');
const statsController = require('../controllers/statsController');
const { authenticate, authorize } = require('../middleware/auth');
const { validate } = require('../middleware/validation');

const router = express.Router();

// 所有统计路由都需要管理员权限
router.use(authenticate, authorize('admin'));

// 仪表板统计
router.get('/dashboard', [
  query('period')
    .optional()
    .isIn(['7d', '30d', '90d', '1y'])
    .withMessage('period 必须为 7d, 30d, 90d, 1y 之一')
], validate, statsController.getDashboardStats);

// 销售报告
router.get('/sales', [
  query('startDate')
    .notEmpty()
    .withMessage('开始日期不能为空')
    .isISO8601()
    .withMessage('开始日期格式不正确 (ISO8601: YYYY-MM-DD)'),
  query('endDate')
    .notEmpty()
    .withMessage('结束日期不能为空')
    .isISO8601()
    .withMessage('结束日期格式不正确 (ISO8601: YYYY-MM-DD)'),
  query('groupBy')
    .optional()
    .isIn(['day', 'week', 'month'])
    .withMessage('groupBy 必须为 day, week, month 之一')
], validate, statsController.getSalesReport);

// 产品报告
router.get('/products', [
  query('page')
    .optional()
    .isInt({ min: 1 })
    .withMessage('页码必须为正整数'),
  query('limit')
    .optional()
    .isInt({ min: 1, max: 100 })
    .withMessage('每页数量必须在1-100之间'),
  query('sortBy')
    .optional()
    .isIn(['totalSold', 'totalRevenue', 'name'])
    .withMessage('sortBy 必须为 totalSold, totalRevenue, name 之一'),
  query('sortOrder')
    .optional()
    .isIn(['ASC', 'DESC'])
    .withMessage('sortOrder 必须为 ASC 或 DESC')
], validate, statsController.getProductReport);

module.exports = router;